package com.zsl.swing.redis.desktop.utils;

import com.vladsch.flexmark.ext.autolink.AutolinkExtension;
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.ast.NodeVisitor;
import com.vladsch.flexmark.util.ast.VisitHandler;
import com.vladsch.flexmark.util.data.MutableDataSet;
import org.apache.commons.io.output.ByteArrayOutputStream;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MdFileUtils {

    private static final String BASE_DIR = "/doc/";

    public static String read(String filename, String ... imgNames){


        StringBuilder content = new StringBuilder();
        try (
                BufferedReader reader = new BufferedReader(new FileReader(MdFileUtils.class.getResource(BASE_DIR + filename).getFile()))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        String mdText = content.toString();
        if(!CollectionUtils.isEmpty(imgNames)){
            for (String imgName : imgNames) {
                String imgBase64 = convertImageToBase64(imgName);
                mdText = mdText.replace("![Image](./" + imgName + ")", "![Image](data:image/png;base64," + imgBase64 +")");
            }
        }


//        mdText.replace("![Image](./", "![Image](file:/");
        String html = convertMarkdownToHTML(mdText);

        html.replace("<img", "<img width=300 height= 200 ");

        return html;
    }

    private static String insertBase64Image(String htmlContent) {
        // 匹配 base64 图片的正则表达式
        Pattern pattern = Pattern.compile("data:image/png;base64,([^'\"]+)");
        Matcher matcher = pattern.matcher(htmlContent);

        // 替换 base64 图片为 img 标签
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String base64Data = matcher.group(1);
            // 将 base64 字符串转换为 byte 数组
//            byte[] imageData = Base64.getDecoder().decode(base64Data);
            // 获取图片在 img 标签中的占位符
            String imgTag = "<img src=\"data:image/png;base64," + base64Data + "\">";
            // 替换 base64 图片为 img 标签
            matcher.appendReplacement(result, imgTag);
        }
        matcher.appendTail(result);
        return result.toString();
    }

    private static String convertMarkdownToHTML(String markdownContent) {
        MutableDataSet options = new MutableDataSet();
        options.set(Parser.EXTENSIONS, Arrays.asList(
                AutolinkExtension.create(),
                StrikethroughExtension.create(),
                TablesExtension.create()
        ));

        Parser parser = Parser.builder(options).build();
        Node document = parser.parse(markdownContent);

        // 将 base64 图片转换为 HTML 标签
        NodeVisitor nodeVisitor = new NodeVisitor(
                new VisitHandler<>(com.vladsch.flexmark.ext.wikilink.WikiLink.class, node -> {
                    // 在这里处理 WikiLink 节点，即 Markdown 文件中的图片
                    // 这里简化为直接输出节点内容，实际应用中需要根据节点内容进行处理
                    System.out.println(node.getChars().toString());

                })
        );
        nodeVisitor.visit(document);

        // 使用默认的 HTML 渲染器将 Markdown 文档渲染为 HTML 字符串
        return com.vladsch.flexmark.html.HtmlRenderer.builder(options).build().render(document);
    }

//    public static String convertMarkdownToHTML(String markdownText) {
//        List<Extension> extensions = Arrays.asList(
////                AutolinkExtension.create(),
////                StrikethroughExtension.create(),
//                TablesExtension.create()
//        );
//
//        Parser parser = Parser.builder().extensions(extensions).build();
//        HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
//
//        return renderer.render(parser.parse(markdownText));
//    }


    public static void main(String[] args) {
        System.out.println(convertImageToBase64("window_show.png"));
    }
    private static String convertImageToBase64(String imgName) {
        try {
            String filename = BASE_DIR  + imgName;

            InputStream in = MdFileUtils.class.getResourceAsStream(filename);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }

            in.close();

            byte[] imageBytes = byteArrayOutputStream.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
